package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"user-app/models"
)

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type UserController struct {
	beego.Controller
}

func (c *UserController) Add() {
	name := c.GetString("name")
	age, _ := c.GetInt("age")
	tel := c.GetString("tel")
	address := c.GetString("address")
	deng := c.GetString("deng")
	quan := c.GetString("quan")
	user := models.User{
		Name:    name,
		Age:     age,
		Tel:     tel,
		Address: address,
		Deng:    deng,
		Quan:    quan,
	}
	err := models.DB.Model(&models.User{}).Create(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: user,
		}
		c.ServeJSON()
	}
}
func (c *UserController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	pageData := make(map[string]interface{})
	var count int64
	var user []models.User
	models.DB.Model(&models.User{}).Count(&count)
	offset := (page - 1) * size
	err := models.DB.Model(&models.User{}).Order("age desc").Offset(offset).Limit(size).Find(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData["count"] = count
		pageData["user"] = user
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: user,
		}
		c.ServeJSON()
	}
}
func (c *UserController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.User{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
